<template>
  <view>
    <image src="../../static/mine-bg.png" class="fixed-bg"></image>
    <view class="setting-content-container">
      <uni-nav-bar background-color="transparent" @clickLeft="handleClick" color="#fff" status-bar="true"
        left-icon="back" :border="none" fixed="true">
        <image src="../../static/logo.png" mode="heightFix" style="height: 44px;margin: 0 auto;"></image>
      </uni-nav-bar>
      <view class="content">
        <view class="setting-content">
          <view class="setting-item mt20">
            <view>头像</view>
            <view class="avatar" @click="changeImage">
              <image v-if="avatar" :src="avatar" style="width:38px;height: 38px;border-radius: 50%;"></image>
              <uni-icons type="person-filled" size="38" color="#a0a0a0" v-else></uni-icons>
            </view>
          </view>
          <view class="division" style="margin: 30rpx 0;">

          </view>
          <view class="setting-item mt20" @click="handleChange('name')">
            <view>用户名</view>
            <view>{{nickName}} <uni-icons type="forward" color="#ababab" size="18"></uni-icons></view>
          </view>
          <view class="division" style="margin: 30rpx 0;">

          </view>
          <view class="setting-item mb20" @click="handleChange('phone')">
            <view>手机号</view>
            <view>{{phone}} <uni-icons type="forward" color="#ababab" size="18"></uni-icons></view>
          </view>
          <view class="division" style="margin: 30rpx 0;">

          </view>
          <view class="setting-item mb20">
            <view>部门</view>
            <view>{{deptName}} <uni-icons type="forward" color="#ababab" size="18"></uni-icons></view>
          </view>
        </view>
        <button type="default" @click="logout" style="margin: 20rpx 0;">退出登录</button>
      </view>
    </view>
    <uni-popup ref="popup" type="center">
      <view class="setting-pop-container">
        <view class="header">
          <text>{{type == 'name' ? '更换用户名' : '更换手机号'}}</text>
          <uni-icons type="closeempty" color="#a0a0a0" size="20" style="float: right;" @click="close"></uni-icons>
        </view>
        <view class="popup-content">
          <block v-if="type == 'name'">
            <view class="input-container">
              <input type="nickname" value="" maxlength="6" v-model="username" placeholder="请输入昵称" />
            </view>
          </block>
          <block v-else>
            <view class="input-container">
              <input type="text" value="" v-model="mobile" placeholder="请输入手机号" />
            </view>
            <view class="input-container">
              <input type="text" value="" v-model="code" placeholder="请输入验证码" />
              <text @click="sendCode">{{codeText}}</text>
            </view>

          </block>
          <button type="default" @click="handleSubmit">更换</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    getSmsCode,
    resettingEnabled,
    getUserInfo,
    updateUser,

  } from '@/apis/user.js'
  import {
    uploadAvatr
  } from '@/apis/upload.js'
  export default {
    data() {
      return {
        nickName: '',
        phone: '',
        title: '更换手机号',
        codeText: '获取验证码',
        mobile: '',
        code: '',
        isSend: false,
        type: 'wx',
        username: '',
        avatar: '',
        deptName: ''
      };
    },
    onLoad() {
      let userinfo = uni.getStorageSync('userinfo')

      this.getUserInfo(userinfo.userId)
    },
    methods: {
      async getUserInfo(id) {
        let res = await getUserInfo(id)
        if (res.code == 200) {
          const userinfo = res.data;
          this.nickName = userinfo.nickName
          this.phone = userinfo.phonenumber || '未绑定'
          this.userId = userinfo.userId
          this.wechat = userinfo.wechat
          this.deptName = userinfo.dept.deptName;
          const info = {
            userName: userinfo.nickName,
            userId: userinfo.userId,
            phonenumber: userinfo.phonenumber,
            deptId: userinfo.dept.deptId
          }
          if (userinfo.avatar) {
            this.avatar = 'https://' + userinfo.avatar;
            info.avatar = this.avatar
          }
          console.log(info)
          uni.setStorageSync('userinfo', info, {
            force: true
          })
        }
      },
      handleClick() {
        uni.navigateBack()
      },
      logout() {
        uni.clearStorage()
        this.handleClick()
      },
      close() {
        this.$refs.popup.close()
        this.isSend = false;
        this.codeText = '获取验证码'
      },
      async changeImage() {
        var _this = this;
        uni.chooseMedia({
          count: 1,
          mediaType: ['image'],
          success(res) {
            let tempFile = res.tempFiles[0];
            _this.avatar = tempFile.tempFilePath
            uploadAvatr(_this.avatar, _this.userId).then(res => {
              console.log(res)
            })
          }
        })
      },
      async sendCode() {
        if (!this.mobile) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          })
          return;
        }
        if (this.isSend) {
          return
        }
        this.isSend = true;
        let i = 60;
        let timer = setInterval(() => {
          this.codeText = `${i--}S`
          if (i == 0) {
            this.isSend = false;
            this.codeText = '获取验证码'
            clearInterval(timer)
          }
        }, 1000)
        let [err, result] = await getSmsCode(this.mobile)
        if (result.statusCode != 200) {
          this.$showtoast(result.data.msg)
        } else {
          this.$showtoast('验证码发送成功')
          this.validateCode = result.data.code
        }

      },
      handleChange(type) {
        this.type = type;
        this.$refs.popup.open()
      },
      async updateUsername() {
        if (!this.username) {

        }
        let res = await updateUser({
          userId: this.userId,
          nickName: this.username
        })
        if (res.code == 200) {
          this.$showtoast('更换用户名成功')
          setTimeout(() => {
            this.getUserInfo(this.userId)
          }, 1000)
          this.close()
        } else {
          this.$showtoast(res.msg)
        }
      },
      async updateMobile() {
        if (!this.mobile) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none'
          })
          return;
        }
        if (!this.code) {
          uni.showToast({
            title: '请输入验证码',
            icon: 'none'
          })
          return;
        }
        if (this.code != this.validateCode) {
          uni.showToast({
            title: '验证码错误，请重新输入',
            icon: 'none'
          })
          return;
        }
        let res = await resettingEnabled({
          phonenumber: this.mobile,
          userId: this.userId,
        })
        const data = res.data;
        if (res.code == 200) {
          this.$showtoast('更换手机号成功')
          setTimeout(() => {
            this.getUserInfo(this.userId)
          }, 1000)
        } else {
          this.$showtoast(res.msg)
        }
        this.close()
      },
      handleSubmit() {
        if (this.type == 'name') {
          this.updateUsername()
        } else {
          this.updateMobile()
        }

      }
    }
  }
</script>

<style lang="scss">
  .setting-content-container {
    position: absolute;
    height: 100vh;
    width: 100vw;
  }

  .content {
    padding: 20rpx;
    height: calc(100vh - 88rpx);
    background-color: #f7f7f7;
  }

  .setting-content {
    padding: 15rpx;
    border-radius: 20rpx;
    background-color: #fff;
  }

  .setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .setting-pop-container {
    width: 500rpx;
    min-height: 470rpx;
    padding: 15rpx 20rpx;
    background-color: #fff;
    border-radius: 20rpx;

    .header {
      padding: 10rpx 0;
      height: 60rpx;
      text-align: center;
      line-height: 60rpx;
      border-bottom: 1px solid #81ded3;
    }

    .input-container {
      display: flex;
      padding-left: 20rpx;
      margin: 40rpx auto;
      height: 58rpx;
      position: relative;
      font-size: 28rpx;
      border-radius: 58rpx;
      border: 1px solid #dcdcdc;

      input {
        height: 100%;
      }

      text {
        position: absolute;
        top: 50%;
        right: 20rpx;
        display: block;
        height: 100%;
        z-index: 1;
        line-height: 58rpx;
        transform: translateY(-50%);
        color: #7bded6;
      }
    }

    button[type=default] {
      height: 58rpx;
      width: 200rpx;
      font-size: 28rpx;
      line-height: 58rpx;
      border-radius: 30rpx;
      color: #fff;
      background-color: #6cd7cd;
    }

    .qrcode-container {
      margin: 40rpx auto;
      padding: 20rpx;
      width: 210rpx;
      height: 210rpx;
      border: 1px solid #7adcd2;
      border-radius: 18rpx;

    }
  }
</style>